<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id' => 'imex-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableClientValidation' => true,
    'clientOptions' => array(
        'validateOnSubmit' => true,
    ),
    'htmlOptions' => array(
        'enctype' => 'multipart/form-data'
    ),
        ));
?>
<?php if ($download): ?>
    <div class="row-fluid">
        <div class="span12">
            <div class="grid simple vertical green">
                <div class="grid-title">
                    <h4>Ваша ссылка для скачивания файла</h4>
                    <div class="tools">
                        <a class="collapse" href="javascript:;"></a>
                        <a class="remove" href="javascript:;"></a>
                    </div>
                </div>
                <div class="grid-body">
                    <p> Нажмите чтобы скачать
                        <a href="<?php echo $download; ?>" target="_blank"><strong><?php echo $download; ?></strong></a>
                    </p>
                </div>
            </div>	 
        </div>
    </div>
<?php endif; ?>
<?php
if ($import) {
    Yii::app()->user->setFlash('danger', $import);
}
?>
<div class="row-fluid">
    <div class="span12">
        <div class="grid simple horizontal red">
            <div class="grid-title ">
                <h4>Импорт и экспорт (Excel)<br /><strong style="color:red;">Во избежании нагрузки на сервер, предлагается экспортировать данных не большого объема, ЧЕМ БОЛЬШЕ ВЫБЕРЕШЬ ТЕМ ДОЛЬШЕ ЖДАТЬ, ИМЕЙ ТЕРПЕНИЕ, И ПОБЕРЕГИ СЕРВЕР !</strong></h4>
                <div class="tools">
                    <a class="collapse" href="javascript:;"></a>
                    <a class="config" data-toggle="modal" href="#grid-config"></a>
                    <a class="reload" href="javascript:;"></a>
                    <a class="remove" href="javascript:;"></a>
                </div>
            </div>
            <div class="grid-body">
                <div class="row-fluid ">
                    <div class="span2">
                        <button class="btn btn-info btn-cons " type="submit"> Экспорт </button>
                    </div>
                    <div class="span4">
                        <div class="radio radio-success">
                            <input type="radio" value="excel2007" name="format" id="excel2007">
                            <label for="excel2007">Excel 2007+</label>
                            <input type="radio"  checked="checked" value="csv" name="format" id="csv">
                            <label for="csv">CSV</label>
                            <input type="radio"  value="csv" name="format" id="txt">
                            <label for="txt">Text</label>
                            <input type="radio"  value="csv" name="format" id="ini">
                            <label for="ini">INI</label>
                            <input type="radio"  value="csv" name="format" id="sql">
                            <label for="sql">SQL</label>
                        </div>
                    </div>
                    <div class="span6">
                        <div class="span6">
                            <button class="btn btn-info btn-cons" id="import_button" disabled="disabled" data-file="" type="submit"> Импорт</button>
                            <input type="checkbox" value="1" checked="checked" disabled="disabled" name="maxim" id="maxim"> Cпец. формат
                            <script type="text/javascript">
                                jQuery(function($) {
                                    jQuery('body').on('click', '#import_button', function() {
                                        var file = $('#import_button').data('file');
                                        var mxm = $('#maxim').is(':checked') ? 1 : 0;
                                        if (file != '')
                                        {
                                            $('div.alert').each(function() {
                                                $(this).remove();
                                            });
                                            var flashMessage = $('<div class="alert"><button data-dismiss="alert" class="close"></button><strong>Загруженый Вами файл обрабатывается, пожалуйста не покиньте эту страницу пока не получите уведомление об успешной обновлении данных либо о возникшей ошибке при обратки файла.</strong></div>');
                                            $('div.page-title').after(flashMessage);
                                            jQuery
                                                    .ajax(
                                                            {
                                                                type: 'post',
                                                                data: {'importedFile': file, maxim: mxm},
                                                                url: '/x8/imex/import',
                                                                cache: false
                                                            }
                                                    )
                                                    .done(function(response)
                                                    {
                                                        response = JSON.parse(response);
                                                        $('div.alert').each(function() {
                                                            $(this).remove();
                                                        });
                                                        var flashMessage = $('<div class="alert alert-' + response.response + '"><button data-dismiss="alert" class="close"></button>' + response.desc + '</div>');
                                                        $('div.page-title').after(flashMessage);
                                                    });
                                        }
                                        return false;
                                    });
                                });
                            </script>
                        </div>
                        <div class="span6">
                            <?php
                            $this->widget('ext.EAjaxUpload.EAjaxUpload', array(
                                'id' => 'uploadFile',
                                'config' => array(
                                    'action' => Yii::app()->createUrl('admin/imex/import'),
                                    'allowedExtensions' => array("xls", "xlsx", 'csv'), //array("jpg","jpeg","gif","exe","mov" and etc...
                                    'sizeLimit' => 20 * 1024 * 1024, // maximum file size in bytes
                                    'minSizeLimit' => 1 * 1024, // minimum file size in bytes
                                    'multiple' => false,
                                    'onComplete' => "js:function(id, fileName, responseJSON){ $('#import_button').data('file',responseJSON.filename).removeAttr('disabled'); }",
                                )
                            ));
                            ?>						
                        </div>
                     
                    </div>
                </div>

                <div class="row-fluid">
                    <div class="span12">
                        <?php
                        foreach ($cats as $cat) {

                            if (!isset($cat['brands']) || sizeof($cat['brands']) < 1)
                                continue;
                            echo '<div class="row-fluid"><div class="span9"><div class="accordion" id="category_' . $cat['id'] . '">
										<div class="accordion-group">
											<div class="accordion-heading"><a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#category_' . $cat['id'] . '" href="#collapse_' . $cat['id'] . '"> ' . $cat['title'] . ' <i class="icon-plus"></i> </a> </div>
											<div style="height: 0px;" id="collapse_' . $cat['id'] . '" class="accordion-body collapse">
												<div class="accordion-inner">';
                            if (isset($cat['services']) && sizeof($cat['services']) > 0) {
                                echo '<div class="row-fluid"><div class="span9"><div class="accordion brand-toggle" id="serviceCategory' . $cat['id'] . '">
											<div class="accordion-group">
												<div class="accordion-heading"><p class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#serviceCategory_' . $cat['id'] . '" href="#serviceCollapse_' . $cat['id'] . '"> Услуги категории <i class="icon-plus"></i> </p> </div>
												<div style="height: 0px;" id="serviceCollapse_' . $cat['id'] . '" class="accordion-body collapse">
													<div class="accordion-inner">';
                                echo '<h4>Выберите нужные услуги</h4><hr /><div class="row-fluid"><div class="span12">';
                                foreach ($cat['services'] as $service) {
                                    echo '<div class="checkbox check-primary">
											<input name="datas[' . $cat['title'] . '#' . $cat['id'] . '][services][' . $service['serviceTitle'] . '#' . $service['serviceId'] . ']"  type="checkbox" value="' . $service['serviceId'] . '" id="service_' . $service['serviceId'] . '">
											<label for="service_' . $service['serviceId'] . '">' . $service['serviceTitle'] . '</label>
										</div>';
                                }
                                echo '</div></div>';
                                echo '</div></div></div></div></div><div class="span3"><button type="button" class="btn btn-default btn-sm btn-large pull-left check-all">Выбрать все</button><button type="button" class="btn btn-danger btn-sm btn-large pull-right uncheck-all">Убрать все</button></div></div>';
                            }
                            if (isset($cat['brands'])) {
                                echo '<h4>Выберите нужных производителей для экспорта</h4><hr /><div class="row-fluid"><div class="span12">';
                                foreach ($cat['brands'] as $brand) {
                                    echo '<div class="checkbox check-primary">
													<input name="datas[' . $cat['title'] . '#' . $cat['id'] . '][' . $brand['title'] . '#' . $brand['id'] . ']" type="checkbox" value="' . $brand['id'] . '" id="bcheck_' . $brand['id'] . '">
													<label for="bcheck_' . $brand['id'] . '">' . $brand['title'] . '</label>
												  </div>';

                                    //if( !isset( $brand[ 'models' ] ) || sizeof( $brand[ 'models' ] ) < 1 )
                                    //	continue;
                                    /* echo '<div class="row-fluid"><div class="span9"><div class="accordion brand-toggle" id="brand_' . $brand[ 'id' ] . '">
                                      <div class="accordion-group">
                                      <div class="accordion-heading"><p class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#brand_' . $brand[ 'id' ] . '" href="#collapse_' . $brand[ 'id' ] . '"> ' . $brand[ 'title' ] . ' <i class="icon-plus"></i> </p> </div>
                                      <div style="height: 0px;" id="collapse_' . $brand[ 'id' ] . '" class="accordion-body collapse">
                                      <div class="accordion-inner">'; */
                                    /*
                                     * if( isset( $brand[ 'models' ] ) )
                                      {
                                      echo '<h4>Выберите нужные модели</h4><hr /><div class="row-fluid"><div class="span12">';
                                      foreach( $brand[ 'models' ] as $model )
                                      {
                                      echo '<div class="checkbox check-primary">
                                      <input name="datas[' . $cat[ 'title' ] . '#' . $cat[ 'id' ] . '][' . $brand[ 'title' ] . '#' . $brand[ 'id' ] . '][' . $model[ 'title' ] . ']" checked="checked" type="checkbox" value="' . $model[ 'id' ] . '" id="model_' . $model[ 'id' ] . '">
                                      <label for="model_' . $model[ 'id' ] . '">' . $model[ 'title' ] . '</label>
                                      </div>';
                                      }
                                      echo '</div></div>';
                                      }
                                     */
                                    //echo '</div></div></div></div></div><div class="span3"><button type="button" class="btn btn-primary btn-sm btn-large pull-left check-all">Выбрать все</button><button type="button" class="btn btn-default  btn-sm btn-large pull-right uncheck-all">Убрать все</button></div></div>';
                                }
                                echo '</div></div>';
                            }
                            echo '</div></div></div></div></div><div class="span3"><button type="button" class="btn btn-default btn-sm btn-large pull-left check-all">Выбрать все</button><button type="button" class="btn btn-danger btn-sm btn-large pull-right uncheck-all">Убрать все</button></div></div>';
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>   
    </div>
</div>
<?php $this->endWidget(); ?>

<script type="text/javascript">
    $(document).ready(function()
    {
        $('button.check-all').on("click", function()
        {
            var block = $(this).parents('.row-fluid:first');
            block.find('input[type=checkbox]').attr("checked", "checked");
            block.find('button[type=button].uncheck-all').removeClass("btn-danger").addClass("btn-default");
            block.find('button[type=button].check-all').removeClass("btn-default").addClass("btn-primary");
        });

        $('button.uncheck-all').on("click", function()
        {
            var block = $(this).parents('.row-fluid:first');
            block.find('input[type=checkbox]').removeAttr("checked");
            block.find('button[type=button].uncheck-all').removeClass("btn-default").addClass("btn-danger");
            block.find('button[type=button].check-all').removeClass("btn-primary").addClass("btn-default");
        });
    });

</script>
